<template>
  <div>
    <div class="layout">

      <img style="width: 200px;height: auto ;"
           src="../../../image/home_search_logo.jpg">

      <searchMusic_Input></searchMusic_Input>
      <div id="searchWord">
        <h3>热搜列表</h3>
      </div>

      <div id="card_list">
        <div v-for="o in this.searchHotData"
             :key="o.index">
          <Card :bordered="false"
                :padding="4"
                @click.native="handleClick(o)"
                style="margin-bottom: 5px;text-align: left; line-height: 32px;border: dashed 1px #DCDFE6;background-color: #f7f7f7;">
            <Row style="display: flex;">
              <div style="width: 30px;"><span style="font-size: 20px;color: red;">{{ o.index }}</span>、</div>
              <div>
                <span style="font-size: 20px;"><a class="recommend"
                     :href="'/searchSong?search='+o.searchWord">{{ o.searchWord }}</a></span>
                <img :src="o.iconUrl"
                     style="width: 16px;margin-left: 5px;" />
              </div>
              <div style="color: #909399;"
                   id="hot_rd">
                热度：
                <span style="color: #2d8cf0;">{{ o.score }}</span>
              </div>

            </Row>
          </Card>
        </div>
      </div>

    </div>
    <!-- Drawer 聊天窗口 -->
    <el-drawer v-if="false"
               :visible.sync="drawerVisible"
               direction="rtl"
               size="450px"
               :before-close="handleClose">
      <div class="chat-container">
        <div class="messages"
             ref="messagesContainer">
          <div v-for="(message, index) in messages"
               :key="index"
               class="message-item"
               :class="{'right': message.isUser}">
            <el-avatar :size="30"
                       style="margin-right: 10px;"
                       src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                       v-if="!message.isUser"></el-avatar>
            <div class="message-content">{{ message.text }}</div>
            <el-avatar :size="30"
                       style="margin-left: 10px;"
                       src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                       v-if="message.isUser"></el-avatar>
          </div>
        </div>

        <!-- 消息输入框 -->
        <el-input v-model="newMessage"
                  placeholder="输入消息..."
                  @keyup.enter="sendMessage"
                  @change="sendMessage"
                  class="chat-input"
                  ref="inputRef"
                  @blur="onBlur"
                  :disabled="isSending" />
        <el-button @click="sendMessage"
                   :loading="isSending"
                   class="send-btn">发送</el-button>
      </div>
    </el-drawer>
  </div>

</template>
<script>
import musicAPI from '@/api/apis/musicAPI.js'
export default {
  data() {
    return {
      value: '',
      searchHotData: [],
      drawerVisible: true, // 控制 Drawer 是否显示
      newMessage: '', // 存储输入框的内容
      messages: [], // 聊天消息记录
      isSending: false, // 控制发送按钮的加载状态
    }
  },
  mounted() {
    this.musicSearchHot()
    this.$store.state.search = ''

    let webSocket = null // 创建一个变量
    if ('WebSocket' in window) {
      // 判断当前的浏览器是否支持WebSocket
      // 如果支持则创建一个WebSocket赋值给刚才创建的变量
      // 后面的路径实际上就是一次请求，但是这里用的是WebSocket协议
      // 记住这个地方后面详细讲到怎么写
      webSocket = new WebSocket(
        'ws://110.41.83.104:8888/api/websocket-server/1'
      )
    } else {
      // 如果不兼容则弹框，该浏览器不支持
      alert('该浏览器不支持')
    }

    /**
     * 当WebSocket创建连接(初始化)会触发该方法
     */
    webSocket.onopen = function (event) {
      console.log('建立连接' + event.data) // 这个代表在浏览器打印日志，跟Java的System.out.println()意思一致
    }

    /**
     * 当WebSocket关闭时候会触发该方法
     */
    webSocket.onclose = function (event) {
      console.log('关闭连接' + event.data) // 同上
    }

    /**
     * 当WebSocket接受消息会触发该方法
     */
    webSocket.onmessage = (event) => {
      this.renderFunc()
      console.log('收到消息：' + event.data)
    }

    /**
     * 当WebSocket连接出错触发该方法
     */
    webSocket.onerror = function (event) {
      console.log('websocket发生错误' + event.data)
    }

    /**
     * 页面关闭，WebSocket关闭
     */
    window.onbeforeunload = function () {
      webSocket.close()
    }
  },
  methods: {
    musicSearchHot() {
      musicAPI.searchHot().then((res) => {
        this.searchHotData = res.data.data
      })
    },

    handleClick(data) {
      this.$router.push('/searchSong?search=' + data.searchWord)
    },

    renderFunc() {
      this.$Notice.success({
        title: 'Notification title',
        desc: 'The desc will hide when you set render.',
        render: (h) => {
          return h('span', [
            'This is created by ',
            h('a', 'render'),
            ' function',
          ])
        },
      })
    },

    showDrawer() {
      this.drawerVisible = true
    },
    handleClose() {
      this.drawerVisible = false
      // 关闭 Drawer 时执行的操作
      console.log('Drawer closed')
    },
    sendMessage() {
      if (!this.newMessage.trim()) return // 防止发送空消息

      this.isSending = true // 设置发送状态
      const message = {
        text: this.newMessage,
        isUser: true, // 标记为用户发送的消息
      }

      // 模拟发送消息后，系统回复
      this.messages.push(message)
      this.newMessage = '' // 清空输入框

      // 模拟系统回复
      setTimeout(() => {
        this.messages.push({
          text: '系统回复: ' + message.text,
          isUser: false, // 系统消息标记为 false
        })
        this.isSending = false // 恢复按钮状态
      }, 100) // 模拟延迟
      // 滚动到底部
      this.scrollToBottom()

      // 回车事件处理，手动设置焦点
      this.$nextTick(() => {
        this.$refs.inputRef.focus()
      })
    },
    onBlur() {
      console.log('sbsbbsbsb')

      // 回车事件处理，手动设置焦点
      this.$nextTick(() => {
        this.$refs.inputRef.focus()
      })
    },
    // 滚动消息容器到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    },
  },
}
</script>

<style>
/* 手机样式 */
@media (max-width: 767px) {
  .layout {
    margin: 0 auto;
    width: 300px;
    margin-top: 50px;
  }

  #searchWord {
    font: italic 16px Arial, sans-serif;
    margin-top: 15px;
  }

  #card_list {
    width: 300px;
    margin-top: 10px;
  }

  #hot_rd {
    position: absolute;
    right: 5px;
  }
}

/* 电脑样式 */
@media (min-width: 1024px) {
  .layout {
    margin: 0 auto;
    width: 600px;
    margin-top: 50px;
  }

  #searchWord {
    font: italic 16px Arial, sans-serif;
    margin-top: 15px;
  }

  #card_list {
    width: 600px;
    margin-top: 10px;
  }

  #hot_rd {
    position: absolute;
    right: 80px;
  }
}

/* 平板样式 */
@media (min-width: 768px) and (max-width: 1024px) {
  /* 平板样式规则 */
}

.recommend {
  color: black;
  margin-left: 5px;
}

.recommend:hover {
  color: #409eff;
}
</style>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.messages {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
}
.message-item.right {
  justify-content: right;
}

.message-content {
  background-color: #f1f1f1;
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
}

.message-item.right .message-content {
  background-color: #409eff;
  color: white;
  align-self: flex-end;
}

.chat-input {
  margin-bottom: 10px;
}

.send-btn {
  align-self: flex-end;
}

/* 滚动条美化 */
.messages::-webkit-scrollbar {
  width: 3px; /* 设置滚动条宽度 */
}

.messages::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道背景色 */
  border-radius: 10px; /* 轨道的圆角 */
}

.messages::-webkit-scrollbar-thumb {
  background-color: rgba(1, 13, 58, 1); /* 滚动条滑块颜色 */
  border-radius: 10px; /* 滑块的圆角 */
}

.messages::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 滚动条滑块悬停时颜色 */
}
</style>